package com.imc.core.listener;

import com.imc.core.utils.DateUtils;
import com.imc.platform.base.user.pojo.User;
import com.imc.platform.frame.pojo.VisitSummary;
import com.imc.platform.frame.repository.VisitSummaryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Created by tanweiping on 2018/9/17.
 */
@Slf4j
@WebListener
public class SessionCount implements HttpSessionListener {

    //public int count=0;//记录session的数量
    public int onlineCount=0;//记录session的数量
    //监听session的创建,synchronized 防并发bug
    public synchronized void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        if (session.getAttribute("currentUser")!=null){
            log.info("【HttpSessionListener监听器】count++  增加");
//            onlineCount++;
//            session.getServletContext().setAttribute("onlineCount", onlineCount);

        }
        //session.getServletContext().setAttribute("count", count);

    }
    @Override
    public synchronized void sessionDestroyed(HttpSessionEvent event) {//监听session的撤销
        log.info("【HttpSessionListener监听器】count--  减少");
        HttpSession session = event.getSession();

        Object onlineCount = session.getServletContext().getAttribute("onlineCount");
        if (onlineCount==null){
            onlineCount = 1;
        }
        if (session.getAttribute("currentUser")!=null){
            int onlineCount_ = Integer.valueOf(String.valueOf(onlineCount)).intValue() - 1;
            session.getServletContext().setAttribute("onlineCount", onlineCount_);
        }
    }
}
